package cn.xingzhen.jfield.ui;

import cn.xingzhen.jfield.componet.*;
import cn.xingzhen.jfield.helper.DialogHelper;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * @author wenqiang
 * @date 2023/5/5
 * @comment 主面板
 */
public class MainFrame extends JFrame {

    private final int width = 750;
    private final int height = 810;
    private final int panelHeight = 26;

    protected File configFile = new File(ToolConfigure.CONFIG_FILE_PATH);

    protected XzComboBox<String> dbType = new XzComboBox<String>("SQLServer", "Oracle", "MySQL");
    protected XzTextField dbHost = new XzTextField();
    protected XzTextField dbPort = new XzTextField("1433");
    protected XzTextField dbUser = new XzTextField();
    protected XzTextField dbPassword = new XzTextField();
    protected XzTextField dbName = new XzTextField();

    protected XzTextField tableName = new XzTextField(240);
    protected XzTextField tableAsName = new XzTextField("a", 50);
    protected XzRadioButton wu = new XzRadioButton("无", true, 50);
    protected XzRadioButton tuoFeng = new XzRadioButton("驼峰", false);
    protected XzRadioButton xiaoXie = new XzRadioButton("小写", false);
    protected XzCheckBox beiZhu = new XzCheckBox("备注");
    protected XzButton doing = new XzButton("运行", 80);

    protected XzCheckBox feiKong = new XzCheckBox("非空注解", false, 100);
    protected XzComboBox<String> fkType = new XzComboBox<String>("NotNull", "NotBlank", "NotEmpty");
    protected XzCheckBox fkWithDB = new XzCheckBox("只添加非空字段", false, 150, false);
    protected XzCheckBox fkMessage = new XzCheckBox("启用消息(备注)", false, 150, false);

    protected XzCheckBox changDu = new XzCheckBox("长度注解", false, 100);
    protected XzRadioButton cdDefault = new XzRadioButton("默认", true, 80);
    protected XzRadioButton cdChinese = new XzRadioButton("中文(len/3)", false, 100);

    protected XzCheckBox riQi = new XzCheckBox("日期注解", false, 100);
    protected XzTextField rqFormat = new XzTextField("yyyy-MM-dd HH:mm:ss", false);

    protected ButtonGroup buttonGroup = new ButtonGroup();

    protected XzRadioButton javaField = new XzRadioButton("Java Field", true, 100);
    protected XzCheckBox jfDateString = new XzCheckBox("日期类型为String", false, 150);
    protected XzCheckBox jfNotNull = new XzCheckBox("只要非空字段", false, 150);

    protected XzRadioButton mbInsert = new XzRadioButton("MyBatis Insert", false, 140);
    protected XzRadioButton mbUpdate = new XzRadioButton("MyBatis Update", false, 140);
    protected XzRadioButton mbSet = new XzRadioButton("MyBatis Set", false, 120);

    protected XzRadioButton sqlResult = new XzRadioButton("SQL结果", false, 100);
    protected XzRadioButton sqlInsert = new XzRadioButton("SQL Insert", false, 100);
    protected XzRadioButton sqlDelete = new XzRadioButton("SQL Delete", false, 100);
    protected XzRadioButton sqlUpdate = new XzRadioButton("SQL Update", false, 100);
    protected XzRadioButton sqlSelect = new XzRadioButton("SQL Select", false, 100);

    //protected XzTextArea showTextArea = new XzTextArea(width - 20, 445);
    protected XzTextArea showTextArea = new XzTextArea();
    protected XzScrollPane scrollPane01 = new XzScrollPane(width - 10, 455);

    private XzPanel createLinePanel() {
        XzPanel panel = new XzPanel(width - 10, panelHeight);
        panel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 0));
        return panel;
    }

    private XzPanel sqlPanel() {
        buttonGroup.add(sqlResult);
        buttonGroup.add(sqlInsert);
        buttonGroup.add(sqlDelete);
        buttonGroup.add(sqlUpdate);
        buttonGroup.add(sqlSelect);
        return createLinePanel()
                .add(sqlResult)
                .add(sqlInsert)
                .add(sqlDelete)
                .add(sqlUpdate)
                .add(sqlSelect);
    }

    private XzPanel mbPanel() {
        buttonGroup.add(mbInsert);
        buttonGroup.add(mbUpdate);
        buttonGroup.add(mbSet);
        return createLinePanel().add(mbInsert).add(mbUpdate).add(mbSet);
    }

    private XzPanel jfPanel() {
        buttonGroup.add(javaField);
        return createLinePanel().add(javaField).add(jfDateString).add(jfNotNull);
    }

    private XzPanel rqPanel() {
        return createLinePanel().add(riQi).add(rqFormat);
    }

    private XzPanel lengthPanel() {
        cdDefault.setEnabled(false);
        cdChinese.setEnabled(false);
        ButtonGroup bg = new ButtonGroup();
        bg.add(cdDefault);
        bg.add(cdChinese);
        return createLinePanel().add(changDu).add(cdDefault).add(cdChinese);
    }

    private XzPanel notNullPanel() {
        return createLinePanel().add(feiKong).add(fkWithDB).add(fkMessage);
    }

    private XzPanel actionPanel() {
        XzPanel actionPanel = new XzPanel(width - 10, panelHeight);
        this.add(actionPanel);
        actionPanel.add(new XzLabel("表名", 40).setAlignment(JLabel.LEFT));
        actionPanel.add(tableName);
        actionPanel.add(new XzLabel("AS", 30).setAlignment(JLabel.CENTER));
        actionPanel.add(tableAsName);
        ButtonGroup bg = new ButtonGroup();
        bg.add(wu);
        bg.add(tuoFeng);
        bg.add(xiaoXie);
        actionPanel.add(wu);
        actionPanel.add(tuoFeng);
        actionPanel.add(xiaoXie);
        actionPanel.add(beiZhu);
        //actionPanel.add(new XzPanel(70));
        //actionPanel.add(Box.createHorizontalStrut(100));
        actionPanel.add(doing);
        doing.addActionListener(new RunAction(this));
        return actionPanel;
    }

    private void initView() {
        this.addListener();

        XzPanel configPanel = new XzPanel(width - 10, 65);
        this.add(configPanel);
        configPanel.add(new XzLabel("数据库")).add(dbType);
        configPanel.add(new XzLabel("HOST")).add(dbHost.setWidth(250));
        configPanel.add(new XzLabel("端口")).add(dbPort.setWidth(90));
        configPanel.add(new XzLabel("用户名")).add(dbUser.setWidth(120));
        configPanel.add(new XzLabel("密码")).add(dbPassword);
        configPanel.add(new XzLabel("实例名")).add(dbName);
        this.add(createSeparator());

        add(actionPanel());
        add(notNullPanel());
        add(lengthPanel());
        add(rqPanel());
        add(jfPanel());
        add(mbPanel());
        add(sqlPanel());
        this.add(createSeparator());
        scrollPane01.setViewportView(showTextArea);
        add(scrollPane01);
        showTextArea.setFont(new Font(null, Font.PLAIN, 16)); // 设置字体
        // 必须设置在jframe添加完组件之后
        JScrollBar jscrollBar = scrollPane01.getVerticalScrollBar();
        if (jscrollBar != null) {
            // 必须先获取一次jscrollBar.getMaximum()，否则滚动不到最底部, swing bug
            jscrollBar.setValue(jscrollBar.getMaximum());
        }
    }

    private JSeparator createSeparator() {
        final JSeparator separator2 = new JSeparator();
        separator2.setPreferredSize(new Dimension(width - 10, 10));
        return separator2;
    }

    private void addListener() {
        //JOptionPane.showMessageDialog(null, "", "提示", JOptionPane.ERROR_MESSAGE);
        dbType.addActionListener(e -> {
            if (dbType == e.getSource()) {
                if (dbType.getSelectedItem().equals("SQLServer")) dbPort.setText("1433");
                if (dbType.getSelectedItem().equals("Oracle")) dbPort.setText("1521");
                if (dbType.getSelectedItem().equals("MySQL")) dbPort.setText("3306");
                /*
                if (dbType.getSelectedIndex() == 0) {
                    dbPort.setText("1433");
                }
                if (dbType.getSelectedIndex() == 1) {
                    dbPort.setText("1521");
                }
                if (dbType.getSelectedIndex() == 2) {
                    dbPort.setText("3306");
                }*/
            }
        });

        feiKong.addChangeListener(e -> {
            if (feiKong.isSelected()) {
                fkWithDB.setEnabled(true);
                fkMessage.setEnabled(true);
            } else {
                fkWithDB.setEnabled(false);
                fkMessage.setEnabled(false);
            }
        });

        changDu.addChangeListener(e -> {
            if (changDu.isSelected()) {
                cdDefault.setEnabled(true);
                cdChinese.setEnabled(true);
            } else {
                cdDefault.setEnabled(false);
                cdChinese.setEnabled(false);
            }
        });

        riQi.addChangeListener(e -> {
            if (riQi.isSelected()) {
                rqFormat.setEnabled(true);
            } else {
                rqFormat.setEnabled(false);
            }
        });

        javaField.addChangeListener(e -> {
            if (javaField.isSelected()) {
                jfDateString.setEnabled(true);
                jfNotNull.setEnabled(true);
                feiKong.setEnabled(true);
                changDu.setEnabled(true);
                riQi.setEnabled(true);
            } else {
                jfDateString.setEnabled(false);
                jfNotNull.setEnabled(false);
                feiKong.setEnabled(false);
                changDu.setEnabled(false);
                riQi.setEnabled(false);
            }
        });
    }

    public MainFrame() {
        this.setTitle("[行真™]根据表生成JavaField(v8.0)");
        this.setIconImage(Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/img/zp.jpg")));
        //设置外观风格
        //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        //刷新jf容器及其内部组件的外观
        //SwingUtilities.updateComponentTreeUI(this);

        // 设置窗口大小
        //this.setBounds(100, 100, 750, 810);
        this.setSize(width, height);
        //能否手动拖动大小
        this.setResizable(false);
        // 把窗口位置设置到屏幕中心
        this.setLocationRelativeTo(null);
        // 当点击窗口的关闭按钮时退出程序（没有这一句，程序不会退出）
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //自动获取焦点
        this.setAutoRequestFocus(true);
        //添加Frame事件监听
        //this.addWindowListener();

        //this.pack(); //窗口大小自动
        //显示窗口，前面创建的信息都在内存中，通过 setVisible(true) 把内存中的窗口显示在屏幕上。
        //this.setVisible(true);

        // 移除默认布局，让界面变成可任意设定坐标位置
        //this.getContentPane().setLayout(null);
        //this.getContentPane().setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
        //JDK 1.7以下要这样设置布局
        this.getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
        this.initView();

        //配置读取
        try {
            if(configFile.exists()) {
                FileInputStream fis = new FileInputStream(configFile);
                Properties properties = new Properties();
                properties.load(fis);
                fis.close();
                this.dbType.setSelectedItem(properties.getProperty("database"));
                this.dbHost.setText(properties.getProperty("database_host"));
                this.dbUser.setText(properties.getProperty("database_user"));
                this.dbPassword.setText(properties.getProperty("database_password"));
                this.dbName.setText(properties.getProperty("database_name"));
                this.dbPort.setText(properties.getProperty("database_port"));
                this.tableName.setText(properties.getProperty("database_table"));
            }
        } catch (Exception e) {
            DialogHelper.warning(e.getMessage());
        }

        //保存配置
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e3) {
                if (!configFile.exists()) {
                    try {
                        configFile.createNewFile();
                    } catch (IOException e) {
                        DialogHelper.error(e);
                    }
                }
                configFile.setWritable(true, true);
                configFile.setReadable(true, true);
                configFile.setExecutable(true, true);
                try(FileOutputStream fos = new FileOutputStream(configFile)) {
                    Properties properties = new Properties();
                    properties.put("database", dbType.getSelectedItem().toString());
                    properties.put("database_host", dbHost.getText());
                    properties.put("database_user", dbUser.getText());
                    properties.put("database_password", dbPassword.getText());
                    properties.put("database_name", dbName.getText());
                    properties.put("database_port", dbPort.getText());
                    properties.put("database_table", tableName.getText());
                    properties.store(fos, "Java Field [xingzhen 719812998@qq.com]");
                } catch (Exception e) {
                    DialogHelper.error(e);
                }
                super.windowClosing(e3);
            }
        });
    }


}
